package com.intco.ait.quotation.api.infrastructure.mybatis.mapper;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.intco.ait.quotation.api.infrastructure.mybatis.entity.menu.MaterialCodingProperty;
import com.intco.ait.quotation.api.infrastructure.mybatis.entity.menu.MaterialCodingPropertySelectItem;
import com.intco.ait.quotation.api.infrastructure.mybatis.entity.encodingPlatform.MaterialCodingPropertyWithItems;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

@DS("sh-mrp")
public interface MenuConfigMapper {

    @Select("SELECT Id,MaterialClass FROM MaterialCodingClass WHERE Enabled = 1 AND ApplyTo = 'PE辅料-六安' " +
            "GROUP BY Id,MaterialClass ORDER BY MIN(SortId);")
    List<Map<String,Object>> getMaterialClass();

    @Select("SELECT * FROM MaterialCodingProperty WHERE MaterialCodingClassId = #{classId} AND Enabled = 1 ORDER BY SortId")
    List<MaterialCodingProperty> getPropertiesByClassId(@Param("classId") Integer classId);

    @Select("SELECT * FROM MaterialCodingPropertySelectItem WHERE MaterialPropertyId = #{propertyId} AND Enabled = 1 ORDER BY SortId")
    List<MaterialCodingPropertySelectItem> getSelectItemsByPropertyId(@Param("propertyId") Integer propertyId);

    /**
     * Return properties for a class and, when the control type indicates a dropdown/select,
     * also populate the select items for that property via a nested select (many).
     */
    @Select("SELECT * FROM MaterialCodingProperty WHERE MaterialCodingClassId = #{classId} AND Enabled = 1 ORDER BY SortId")
    @Results({
            @Result(column = "Id", property = "id"),
            @Result(column = "MaterialCodingClassId", property = "materialCodingClassId"),
            @Result(column = "PropertyName", property = "propertyName"),
            @Result(column = "ControlType", property = "controlType"),
            @Result(column = "ControlWidth", property = "controlWidth"),
            @Result(column = "DecimalDigits", property = "decimalDigits"),
            @Result(column = "Prefix", property = "prefix"),
            @Result(column = "Suffix", property = "suffix"),
            @Result(column = "SortId", property = "sortId"),
            @Result(column = "AllowNull", property = "allowNull"),
            @Result(column = "KeepZero", property = "keepZero"),
            @Result(column = "Enabled", property = "enabled"),
            // For select/dropdown controls, fetch select items using the property Id
            @Result(column = "Id", property = "selectItems",
                    many = @Many(select = "com.intco.ait.quotation.api.infrastructure.mybatis.mapper.MenuConfigMapper.getSelectItemsByPropertyId"))
    })
    List<MaterialCodingPropertyWithItems> getPropertiesWithItemsByClassId(@Param("classId") Integer classId);
}
